package cn.chinasyq.photoquan.user.fragment;

import android.app.Dialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.RelativeLayout;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;

import cn.chinasyq.photoquan.R;
import cn.chinasyq.photoquan.user.activity.LoginActivity;
import cn.chinasyq.photoquan.user.bean.UserInfo;
import cn.chinasyq.photoquan.user.mode.UserMode;
import cn.chinasyq.photoquan.util.BitmapUtil;
import cn.chinasyq.photoquan.util.CameraHead;
import cn.chinasyq.photoquan.util.DialogUtil;
import cn.chinasyq.photoquan.view.CircleImageView;
import cn.master.util.utils.ToastUtil;
import cn.master.volley.commons.VolleyHelper;
import cn.master.volley.models.response.handler.ResponseHandler;

/**
 * 个人头像
 */
public class HeadPortraitFragment extends Fragment implements
        OnClickListener, ResponseHandler.OnSucceedListener, ResponseHandler.OnNeedLoginListener,
        ResponseHandler.OnFailedListener {

    @SuppressWarnings("unused")
    private static final String TAG = HeadPortraitFragment.class.getName();
    private static final String TAG_UPLOAD = "UPLOAD";

    private RelativeLayout rlytHeadPortrait = null;
    private CircleImageView ivHeadPortrait = null;

    private View view = null;

    private Dialog waitForDialog = null;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_head_portrait, container,
                false);
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initComponent();
        waitForDialog = DialogUtil.createProgressDialog(getActivity());
        waitForDialog.setCancelable(false);
        waitForDialog.setCanceledOnTouchOutside(false);
    }

    @Override
    public void onResume() {
        loadData();
        super.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
    }


    /**
     * 初始化组件
     */
    private void initComponent() {
        rlytHeadPortrait = (RelativeLayout) view
                .findViewById(R.id.rlyt_head_portrait);
        rlytHeadPortrait.setOnClickListener(this);
        ivHeadPortrait = (CircleImageView) view.findViewById(R.id.iv_head_portrait);
        ivHeadPortrait.setOnClickListener(this);
    }

    private void loadData() {
        ivHeadPortrait.setImageUrl(UserMode.getCurrentUserInfo(getActivity()).getLogo(), VolleyHelper.getImageLoader());
    }

    @Override
    public void onClick(View v) {
        callObtainPicture();
    }

    /**
     * 调用头像获取方式
     */
    private void callObtainPicture() {
        CameraHead.selectModeDialog(this);
    }

    /**
     * 上传头像
     */
    private void uploadiHeadPortrait(File bitmap) {
        waitForDialog.show();
        ResponseHandler handler = new ResponseHandler(TAG_UPLOAD);
        handler.setOnSucceedListener(this);
        handler.setOnNeedLoginListener(this);
        handler.setOnFailedListener(this);
        UserMode.uploadUserHeadPhoto(getActivity(), bitmap, handler);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.e(TAG, "onActivityResult");
        Uri bitmap = null;
        try {
            bitmap = CameraHead.callbackZoom(this, requestCode, resultCode, data, 260, 260);
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (bitmap!=null){
            BitmapUtil.compressBitmap(BitmapUtil.convertUri2FilePath(getActivity(), bitmap), 50);
            uploadiHeadPortrait(new File(BitmapUtil.convertUri2FilePath(getActivity(), bitmap)));
        }
    }

    @Override
    public void onFailed(String tag, ResponseHandler.FailedStatus status, int resultCode, String msg) {
        if (msg == null) {
            switch (status) {
                case DATA_ERROR:
                    ToastUtil.show(getActivity(), R.string.tip_data_error);
                    break;
                case NETWORK_ERROR:
                    ToastUtil.show(getActivity(), R.string.servererrortips);
                    break;
            }
        } else {
            ToastUtil.show(getActivity(), msg);
        }
        closeWaitForDialog();
    }

    @Override
    public void onNeedLogin(String tag) {
        closeWaitForDialog();
        startActivity(new Intent(getActivity(), LoginActivity.class));
    }

    @Override
    public void onSucceed(String tag, boolean isCache, Object data) {
        closeWaitForDialog();
        try {
            UserMode.save(getActivity(), (UserInfo) data);
            loadData();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void closeWaitForDialog() {
        if (waitForDialog != null && waitForDialog.isShowing()) {
            waitForDialog.dismiss();
        }
    }
}
